package com.zs.grain.ui

import android.app.*
import android.content.ComponentName
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.media.AudioManager
import android.os.Bundle
import android.text.InputType
import android.text.TextUtils
import android.view.View
import android.widget.*
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.clockkotlin.databaseClockAlarm.AlarmSignal
import com.jeremyliao.liveeventbus.LiveEventBus
import com.xnkj1688.semplibrary.mvvm.*
import com.zs.grain.*
import com.zs.grain.databinding.FragmentSettingBinding
import com.zs.grain.tool.XDialog
import com.xnkj1688.semplibrary.dialog.DialogResult
import com.xnkj1688.semplibrary.dialog.InputNumberDialog
import com.xnkj1688.semplibrary.recyclerview.ItemView
import com.zs.grain.tool.clockManage.LocalDataBase
import com.zslibrary.BusMaster.BusMaster
import com.zslibrary.Enum.BoardId
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_setting.*
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

@Route(path = ARouterPath.SettingFragment)
class SettingFragment : BaseMvvmFragment<FragmentSettingBinding, SettingViewModel>(),SeekBar.OnSeekBarChangeListener {

    override val layoutId = R.layout.fragment_setting
    val advertisementItemView = ItemView<String>(BR.vm, R.layout.item_list5)
    var uvLightHasSetted = false
    var rebootHasSetted = false
    var timerVol1HasSetted = false
    var timerVol2HasSetted = false
    var uvLightLastTime = "10"
    override fun initViewModel(binding: FragmentSettingBinding) {
        binding.vm = this.mViewModel
        binding.view = this

        binding.voiceSeekBar.setOnSeekBarChangeListener(this)
        binding.voiceSeekBar2.setOnSeekBarChangeListener(this)
        initViews(binding)
        initAction(binding)
        LiveEventBus.get("vol1", Int::class.java)
            .observeStickyForever() {
                binding.voiceSeekBar.setProgress(it)//.subscribe({}, {})
            }
        LiveEventBus.get("vol2", Int::class.java)
            .observeStickyForever() {
                binding.voiceSeekBar.setProgress(it)//.subscribe({}, {})
            }
    }

    fun initAction(binding:FragmentSettingBinding){
        Single.just("")
            .subscribeOn(Schedulers.io())
            .subscribe({
                if(mViewModel.isAREnable) rebootHasSetted=true
                if(mViewModel.isVol1Enable) timerVol1HasSetted=true
                if(mViewModel.isVol2Enable) timerVol2HasSetted=true
                if(mViewModel.isUVLightEnable) uvLightHasSetted = true
            },{
                it.printStackTrace()
            })

    }

    fun initViews(binding:FragmentSettingBinding){
        Single.just("")
            .subscribeOn(Schedulers.io())
            .subscribe({
                val am = context?.getSystemService(Context.AUDIO_SERVICE) as AudioManager
                val barValue = am.getStreamVolume(AudioManager.STREAM_MUSIC)
                binding.voiceSeekBar.setProgress((barValue+1)*6)
                val barValue2 = am.getStreamVolume(AudioManager.STREAM_NOTIFICATION)
                binding.voiceSeekBar2.setProgress((barValue2+1)*12)
                uvLightLastTime = mViewModel.uvLightLTime?:"10"
                binding.uvLastTime.setText(uvLightLastTime)
            },{
                it.printStackTrace()
            })
    }

    override fun onUiNotify(name: String, bundle: Bundle) {
        super.onUiNotify(name, bundle)
        when (name) {
            "SoftUpdate"->{
                showProgressDialog("软件升级", "升级中......",false)
            }
            "CraftDownload"->{
                showProgressDialog("工艺下载", "若完成将自动重启......",false)
            }
            "ShowProgress" -> {
                showProgressDialog("部件测试", "测试中......",false)
            }
            "AdsProgress" -> {
                showProgressDialog("广告上传", "上传中......",true)
            }
            "HideProgress" -> {
                hideProgressDialog()
            }
            "Quit" -> {
                var homeIntent = Intent(Intent.ACTION_MAIN, null)
                homeIntent.addCategory(Intent.CATEGORY_HOME)
                val list = this.activity!!.packageManager.queryIntentActivities(homeIntent, 0)
                val info = list[0]
                val pkg = info.activityInfo.packageName
                val cls = info.activityInfo.name
                val componet = ComponentName(pkg, cls)
                homeIntent = Intent()
                homeIntent.component = componet
                startActivity(homeIntent)
                ViewManager.instance.exitApp(this.activity!!)
            }
            "Reboot"->{
                val componetName =  ComponentName("com.example.reboottest",
                    "com.example.reboottest.MainActivity");
                val intent =  Intent();
                intent.setComponent(componetName);
                this.context?.startActivity(intent);
            }
        }
    }

    internal var progressingView: ProgressDialog? = null
    // 显示进度
    fun showProgressDialog(title: String, msg: String,dismissEnable:Boolean) {
        if (TextUtils.isEmpty(msg) || TextUtils.isEmpty(title)) {
            return
        }
        if (progressingView == null) {
            progressingView = ProgressDialog(this.activity)//1.创建一个ProgressDialog的实例
        }
        progressingView!!.setTitle(title)//2.设置标题
        progressingView!!.setMessage(msg)
//        progressingView!!.setCancelable(false)//4.设置可否用back键关闭对话框
        progressingView!!.setCanceledOnTouchOutside(dismissEnable)
        progressingView!!.show()
    }

    fun hideProgressDialog() {
        if (progressingView == null) {
            return
        }
        progressingView!!.hide()
    }

    fun onGetSettingFromCloud() {
        val mcb = view?.findViewById<CheckBox>(R.id.machineInfo)
        val pcb = view?.findViewById<CheckBox>(R.id.productInfo)
        val scb = view?.findViewById<CheckBox>(R.id.sysInfo)
        val isMEnable = mcb!!.isChecked()
        val isPEnable = pcb!!.isChecked()
        val isSEnable = scb!!.isChecked()
        if(isMEnable==false && isPEnable==false && isSEnable==false) Toast.makeText(context,"请选择至少一项",Toast.LENGTH_SHORT).show()
        else{
            var dlgInput = XDialog(this.activity, R.style.Dialog)
            if (dlgInput.showDialog() !== DialogResult.OK) return
            this.mViewModel.mDataService.insertLog("Operation:获取数据")
            mViewModel.getSettingFromCloud(isMEnable,isPEnable,isSEnable)
        }
    }

    fun onUpgradeIoAppF() {
        var dlgInput = XDialog(this.activity, R.style.Dialog)
        if (dlgInput.showDialog() !== DialogResult.OK) return
        mViewModel.onUpgradeIoApp()
    }

    var dialog: Dialog? = null;
    fun onShowCupBoot(){
        dialog = CommonDialog.Builder(this.context!!)
            .setTitle(mViewModel.hardwareVersion)//"123")//
            .setTitle2(mViewModel.ioAppVersion)//mViewModel.ioAppVersion
            .setTitle3(mViewModel.ioBootVersion)//mViewModel.ioBootVersion
            .setTitle4(mViewModel.cupAppVersion)//mViewModel.cupAppVersion
            .setTitle5(mViewModel.cupBootVersion)//mViewModel.cupBootVersion
            //.setMessage(R.string.CupBootVersion2.toString())
            .setPositiveButton("备用", DialogInterface.OnClickListener { p0, p1 ->
                p0?.dismiss()
                //this.onUiNotify("ShowProgress", Bundle())
            })
            .setNegativeButton("隐藏", DialogInterface.OnClickListener { p0, p1 ->
                p0?.dismiss()

            })
            .setOtherButton("升级", DialogInterface.OnClickListener { p0, p1 ->
                p0?.dismiss()

            })
            .setOther4Button("升级", DialogInterface.OnClickListener { p0, p1 ->
                //p0?.dismiss()
                dialog = CommonDialog.Builder(this.context!!)
                    .setTitle("升级IO版应用")
                    .setPositiveButton("确定", DialogInterface.OnClickListener { p0, p1 ->
                        p0?.dismiss()
                        mViewModel.onUpgradeIoApp()
                    })
                    .setNegativeButton("取消", DialogInterface.OnClickListener { p0, p1 ->
                        p0?.dismiss()
                        //BusMaster.getInstance(context).cancelDurationTest(componentId.toShort(), Id.toShort())
                    })
                    .setWith(1.0f)
                    .create(
                        false,
                        R.layout.dialog_toast1,
                        R.id.yesButton,
                        R.id.noButton
                    );
                dialog?.show()
            })
            .setOther5Button("升级", DialogInterface.OnClickListener { p0, p1 ->
                p0?.dismiss()
                mViewModel.onUpgradeIoBoot()
            })
            .setOther6Button("升级", DialogInterface.OnClickListener { p0, p1 ->
                //p0?.dismiss()
                dialog = CommonDialog.Builder(this.context!!)
                    .setTitle("升级CUP版应用")
                    .setPositiveButton("确定", DialogInterface.OnClickListener { p0, p1 ->
                        p0?.dismiss()
                        mViewModel.onUpgradeCupApp()
                    })
                    .setNegativeButton("取消", DialogInterface.OnClickListener { p0, p1 ->
                        p0?.dismiss()
                        //BusMaster.getInstance(context).cancelDurationTest(componentId.toShort(), Id.toShort())
                    })
                    .setWith(1.0f)
                    .create(
                        false,
                        R.layout.dialog_toast1,
                        R.id.yesButton,
                        R.id.noButton
                    );
                dialog?.show()
            })
            .setOther7Button("升级", DialogInterface.OnClickListener { p0, p1 ->
                p0?.dismiss()
                mViewModel.onUpgradeCupBoot()
            })
            .setWith(1.0f)//0.77f
            .create(false,R.layout.dialog_update,R.id.yesButton,R.id.noButton,R.id.update1,R.id.update2,R.id.update3,R.id.update4,R.id.update5)
            //.create(false,R.layout.dialog_yes_no,R.id.yesButton,R.id.noButton)
            dialog?.show()
    }


    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean){
        if(fromUser){
            var streamType = 3
            var progressReal:Int = -1
            val am = context?.getSystemService(Context.AUDIO_SERVICE) as AudioManager
            if(seekBar?.getId()==R.id.voiceSeekBar){
                when(progress) {
                    in 0..5 -> {progressReal=0}
                    in 97..100 -> {progressReal=15}
                    else -> {progressReal = progress / 6 - 1}
                }
            }else if(seekBar?.getId()==R.id.voiceSeekBar2){
                streamType = 5
                when(progress) {
                    in 0..23 -> {progressReal=1}
                    in 97..100 -> {progressReal=15}
                    else -> {progressReal = progress / 12 - 1}
                }
            }
            mViewModel.startAdjustVolumn(streamType)
            mViewModel.changeVolText(streamType,progress)
            am.setStreamVolume(streamType,progressReal,AudioManager.FLAG_PLAY_SOUND)
        }
    }
    override fun onStartTrackingTouch(seek: SeekBar) {
        // write custom code for progress is started
    }

    override fun onStopTrackingTouch(seek: SeekBar) {
        // write custom code for progress is stopped
        //Toast.makeText(context,"Progress is: " + seek.progress + "%",Toast.LENGTH_SHORT).show()
    }

    private var alarmMgr:AlarmManager? = null
    private lateinit var alarmIntent:PendingIntent

    //    var alarmMgr = context?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
//    var alarmIntent = Intent(context, AlarmReceiver::class.java).let { intent ->
//        PendingIntent.getBroadcast(context, 0, intent, 0)
//    }
    fun onChangeTimerVoiceState(){
        val volSwitchEnable = view?.findViewById<Switch>(R.id.volSwitch)
        if(!volSwitchEnable!!.isChecked()) {
            timerVol1HasSetted = false
            timerVol2HasSetted = false
            var timerVolumnButton1 = view?.findViewById<Button>(R.id.timerVolumn)
            timerVolumnButton1?.setText("设定1")
            var timerVolumnButton2 = view?.findViewById<Button>(R.id.timerVolumn2)
            timerVolumnButton2?.setText("设定2")
            Toast.makeText(context, "定时调节音量已取消", Toast.LENGTH_SHORT).show()
            if(alarmMgr!=null){//本页设的定时重启
                alarmMgr!!.cancel(alarmIntent)
            }else{//系统设的定时重启
                this.mViewModel.mTimerService.cancelTimer("vol")
            }
        }else
            Toast.makeText(context, "定时调节音量已开启", Toast.LENGTH_SHORT).show()
    }
    private lateinit var uvTimeDialog: InputNumberDialog
    fun onUVLastTimeSet(){
        uvTimeDialog = InputNumberDialog(context, R.style.Dialog)
        var dlg = uvTimeDialog
        dlg.text = ""
        dlg.mInputType = InputType.TYPE_CLASS_NUMBER// or InputType.TYPE_NUMBER_VARIATION_PASSWORD
        dlg.setCancelable(false)
        dlg.show()
        dlg.findViewById<View>(R.id.btnConfirm).setOnClickListener {
            var tv = view?.findViewById<TextView>(R.id.uvLastTime)
            if(dlg.text.toString()!="") {
                tv?.text = Math.floor(dlg.text.toDouble()).toInt().toString()//Integer.parseInt防止前面都为0
                uvLightLastTime = Math.floor(dlg.text.toDouble()).toInt().toString()//Integer.parseInt(dlg.text).toString()
            }//Toast.makeText(context,dlg.text.toString(),Toast.LENGTH_SHORT).show()
            if(uvLightLastTime=="0" || dlg.text.toString()=="")
                Toast.makeText(context,"输入有误,请重新输入!",Toast.LENGTH_SHORT).show()
            else dlg.dismiss()
        }
    }

    fun onChangeUVLightState(){
        LocalDataBase.deleteAlarm("uvlight")
        val arSwitchEnable = view?.findViewById<Switch>(R.id.uvLightSwitch)
        if(!arSwitchEnable!!.isChecked()) {
            uvLightHasSetted = false
            var settingTimeButton = view?.findViewById<Button>(R.id.uvLightAutoSetting)
            settingTimeButton?.setText("设定时间")
            Toast.makeText(context, "自动UV灯已取消", Toast.LENGTH_SHORT).show()
            if(alarmMgr!=null){//本页设的定时重启
                alarmMgr!!.cancel(alarmIntent)
            }else{//系统设的定时重启
                this.mViewModel.mTimerService.cancelTimer("uvlight")
            }
        }else
            Toast.makeText(context, "自动UV灯已开启", Toast.LENGTH_SHORT).show()
    }

    fun onChangeAutoRestartState() {
        val arSwitchEnable = view?.findViewById<Switch>(R.id.autoSwitch)
        if(!arSwitchEnable!!.isChecked()) {
            rebootHasSetted = false
            var settingTimeButton = view?.findViewById<Button>(R.id.restartSettingTime)
            settingTimeButton?.setText("设定时间")
            Toast.makeText(context, "自动重启已取消", Toast.LENGTH_SHORT).show()
            if(alarmMgr!=null){//本页设的定时重启
                alarmMgr!!.cancel(alarmIntent)
            }else{//系统设的定时重启
                this.mViewModel.mTimerService.cancelTimer("reboot")
            }
        }else
            Toast.makeText(context, "自动重启已开启", Toast.LENGTH_SHORT).show()
    }

    fun onSetUVLight(){
        var switchEnable = view?.findViewById<Switch>(R.id.uvLightSwitch)
        if(switchEnable!!.isChecked()) {
            if(!uvLightHasSetted) {
                uvLightHasSetted = true
                val cal = Calendar.getInstance()
                val timeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
                    cal.set(Calendar.HOUR_OF_DAY, hour)
                    cal.set(Calendar.MINUTE, minute)
                    cal.set(Calendar.SECOND, 0)
                    cal.set(Calendar.MILLISECOND, 0)
                    var settingTimeButton = view?.findViewById<Button>(R.id.uvLightAutoSetting)
                    settingTimeButton?.setText(hour.toString() + ":" + minute.toString())
                    val clockTime: Date = cal.time
                    val calendarNow = Calendar.getInstance()
                    val currentTime = calendarNow.time
                    if (clockTime.time <= currentTime.time) {
                        cal.timeInMillis += TimeUnit.HOURS.toMillis(24)
                    }

                    alarmMgr = context?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
                    alarmIntent = Intent(context, UVLightReceiver::class.java).let { intent ->
                        PendingIntent.getBroadcast(context, 0, intent, 0)
                    }
                    val sdFormatter = SimpleDateFormat("MM-dd HH:mm")
                    sdFormatter.timeZone = TimeZone.getTimeZone("GMT+8")
                    val info = AlarmManager.AlarmClockInfo(cal.timeInMillis, alarmIntent)
                    alarmMgr?.setAlarmClock(info, alarmIntent)
                    LocalDataBase.addAlarm(
                        getString(R.string.time_format_string, hour, minute),
                        "uvlight:"+uvLightLastTime
                    )
                }
                TimePickerDialog(
                    context, timeSetListener, cal.get(Calendar.HOUR_OF_DAY),
                    cal.get(Calendar.MINUTE), true
                ).show()
            }else Toast.makeText(context,"重设请切换开关",Toast.LENGTH_SHORT).show()
        }else{Toast.makeText(context,"请先启用功能",Toast.LENGTH_SHORT).show()}
    }

    fun onSetRestart2(){
        //if(mViewModel.isAREnabld)

        var switchEnable = view?.findViewById<Switch>(R.id.autoSwitch)
        if(switchEnable!!.isChecked()) {
            if(!rebootHasSetted) {
                rebootHasSetted = true
                val cal = Calendar.getInstance()
                val timeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
                    cal.set(Calendar.HOUR_OF_DAY, hour)
                    cal.set(Calendar.MINUTE, minute)
                    cal.set(Calendar.SECOND, 0)
                    cal.set(Calendar.MILLISECOND, 0)
                    var settingTimeButton = view?.findViewById<Button>(R.id.restartSettingTime)
                    settingTimeButton?.setText(hour.toString() + ":" + minute.toString())

                    val clockTime: Date = cal.time
                    val calendarNow = Calendar.getInstance()
                    val currentTime = calendarNow.time
                    if (clockTime.time <= currentTime.time) {
                        cal.timeInMillis += TimeUnit.HOURS.toMillis(24)
                    }

                    alarmMgr = context?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
                    alarmIntent = Intent(context, AlarmReceiver::class.java).let { intent ->
                        PendingIntent.getBroadcast(context, 0, intent, 0)
                    }
                    val sdFormatter = SimpleDateFormat("MM-dd HH:mm")
                    sdFormatter.timeZone = TimeZone.getTimeZone("GMT+8")
                    val info = AlarmManager.AlarmClockInfo(cal.timeInMillis, alarmIntent)
                    alarmMgr?.setAlarmClock(info, alarmIntent)
                    LocalDataBase.addAlarm(
                        getString(R.string.time_format_string, hour, minute),
                        "reboot"
                    )
                }
                TimePickerDialog(
                    context, timeSetListener, cal.get(Calendar.HOUR_OF_DAY),
                    cal.get(Calendar.MINUTE), true
                ).show()
            }else Toast.makeText(context,"重设请切换开关",Toast.LENGTH_SHORT).show()
        }else{Toast.makeText(context,"请先启用功能",Toast.LENGTH_SHORT).show()}
    }

    fun onShowApp(){
        CommonDialog.Builder(this.context!!)
            .setTitle("人机软件:"+mViewModel.appVersion)
            .setNegativeButton("隐藏", DialogInterface.OnClickListener { p0, p1 ->
                p0?.dismiss()
            })
            .setPositiveButton("升级",DialogInterface.OnClickListener { p0, p1 ->
                p0?.dismiss()
                mViewModel.onUpgradeApp()
            })
            .setWith(1.0f)//0.77f
            .create(false,R.layout.dialog_update_app,R.id.yesButton,R.id.noButton)
            .show()
    }

    fun onUpgradeAppF() {
        var dlgInput = XDialog(this.activity, R.style.Dialog)
        if (dlgInput.showDialog() !== DialogResult.OK) return
        mViewModel.onUpgradeApp()
    }

    fun onUpgradeCraftF() {
        //this.mViewModel.mDataService.insertLog("Operation:下载工艺")
        CommonDialog.Builder(this.context!!)
            .setTitle("下载完成将自动重启,未下载完成请重试")
            .setNegativeButton("取消", DialogInterface.OnClickListener { p0, p1 ->
                p0?.dismiss()
            })
            .setPositiveButton("下载",DialogInterface.OnClickListener { p0, p1 ->
                p0?.dismiss()
                mViewModel.onUpgradeCraft()
            })
            .setWith(1.0f)//0.77f
            .create(false,R.layout.dialog_update_app,R.id.yesButton,R.id.noButton)
            .show()
    }

    private var selectedHour = 0
    private var selectedMinute = 0
    fun confirmTime2(){
        val currentTime = Calendar.getInstance()
        var hour = currentTime.get(Calendar.HOUR_OF_DAY)
        var minute = currentTime.get(Calendar.MINUTE)

        val listener = TimePickerDialog.OnTimeSetListener { timePicker, selectedHour, selectedMinute ->
            this.selectedHour = selectedHour
            this.selectedMinute = selectedMinute
        }

        val timePicker = TimePickerDialog(context, listener, hour, minute, true)
        timePicker.show()
    }

    fun voiceAutoTimer(){
        var switchEnable = view?.findViewById<Switch>(R.id.volSwitch)
        if(switchEnable!!.isChecked()) {
            if(!timerVol1HasSetted) {

                val cal = Calendar.getInstance()
                val timeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
                    cal.set(Calendar.HOUR_OF_DAY, hour)
                    cal.set(Calendar.MINUTE, minute)
                    cal.set(Calendar.SECOND, 0)
                    cal.set(Calendar.MILLISECOND, 0)

                    val am = context!!.getSystemService(Context.AUDIO_SERVICE) as AudioManager
                    val curVol = (am.getStreamVolume(AudioManager.STREAM_MUSIC)+1)*6

                    var timerVolumnButton = view?.findViewById<Button>(R.id.timerVolumn)
                    var result = hour.toString() + ":" + minute.toString() + " vol:" + curVol.toString()
                    timerVolumnButton?.setText(result)

                    val clockTime: Date = cal.time
                    val calendarNow = Calendar.getInstance()
                    val currentTime = calendarNow.time
                    if (clockTime.time <= currentTime.time) {
                        cal.timeInMillis += TimeUnit.HOURS.toMillis(24)
                    }

                    alarmMgr = context?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
                    alarmIntent = Intent(context, AlarmReceiver1::class.java).let { intent ->
                        intent.putExtra("volumn1",curVol)
                        PendingIntent.getBroadcast(context, 1, intent, 0)
                    }
                    val sdFormatter = SimpleDateFormat("MM-dd HH:mm")
                    sdFormatter.timeZone = TimeZone.getTimeZone("GMT+8")
                    val info = AlarmManager.AlarmClockInfo(cal.timeInMillis, alarmIntent)
                    alarmMgr?.setAlarmClock(info,alarmIntent)

                    LocalDataBase.addAlarm(getString(R.string.time_format_string,hour,minute),"vol1:"+curVol.toString())
                    timerVol1HasSetted=true
                }
                TimePickerDialog(context,timeSetListener,cal.get(Calendar.HOUR_OF_DAY),
                    cal.get(Calendar.MINUTE), true).show()
            }else Toast.makeText(context,"重设请切换开关",Toast.LENGTH_SHORT).show()
        }else{
            Toast.makeText(context,"请先启用功能",Toast.LENGTH_SHORT).show()
        }
    }

    fun voiceReduce(streamType:Int){
        mViewModel.onVoiceReduce(streamType)
        updateVolumnSeekBar(streamType)
    }

    fun updateVolumnSeekBar(streamType:Int){
        if(streamType==3) {
            val sb = view?.findViewById<SeekBar>(R.id.voiceSeekBar)
            val am = context?.getSystemService(Context.AUDIO_SERVICE) as AudioManager
            var volumnCurrent = am.getStreamVolume(AudioManager.STREAM_MUSIC)
            sb?.setProgress((volumnCurrent + 1) * 6)
        }else{
            val sb = view?.findViewById<SeekBar>(R.id.voiceSeekBar2)
            val am = context?.getSystemService(Context.AUDIO_SERVICE) as AudioManager
            var volumnCurrent = am.getStreamVolume(AudioManager.STREAM_NOTIFICATION)
            sb?.setProgress((volumnCurrent + 1) * 12)
        }
    }

    fun voiceIncrease(streamType:Int){
        mViewModel.onVoiceIncrease(streamType)
        updateVolumnSeekBar(streamType)
    }

    fun voiceAutoTimer2(){
        var switchEnable = view?.findViewById<Switch>(R.id.volSwitch)
        if(switchEnable!!.isChecked()) {
            if(!timerVol2HasSetted) {

                val cal = Calendar.getInstance()
                val timeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
                    cal.set(Calendar.HOUR_OF_DAY, hour)
                    cal.set(Calendar.MINUTE, minute)
                    cal.set(Calendar.SECOND, 0)
                    cal.set(Calendar.MILLISECOND, 0)

                    val am = context!!.getSystemService(Context.AUDIO_SERVICE) as AudioManager
                    val curVol = (am.getStreamVolume(AudioManager.STREAM_MUSIC)+1)*6

                    var result = hour.toString() + ":" + minute.toString() + " vol:" + curVol.toString()
                    var timerVolumnButton = view?.findViewById<Button>(R.id.timerVolumn2)
                    timerVolumnButton?.setText(result)

                    val clockTime: Date = cal.time
                    val calendarNow = Calendar.getInstance()
                    val currentTime = calendarNow.time
                    if (clockTime.time <= currentTime.time) {
                        cal.timeInMillis += TimeUnit.HOURS.toMillis(24)
                    }

                    alarmMgr = context?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
                    alarmIntent = Intent(context, AlarmReceiver2::class.java).let { intent ->
                        intent.putExtra("volumn2",curVol)
                        PendingIntent.getBroadcast(context, 2, intent, 0)
                    }
                    val sdFormatter = SimpleDateFormat("MM-dd HH:mm")
                    sdFormatter.timeZone = TimeZone.getTimeZone("GMT+8")
                    val info = AlarmManager.AlarmClockInfo(cal.timeInMillis, alarmIntent)
                    alarmMgr?.setAlarmClock(info,alarmIntent)

                    LocalDataBase.addAlarm(getString(R.string.time_format_string,hour,minute),"vol2:"+curVol.toString())
                    timerVol2HasSetted=true
                }
                TimePickerDialog(context,timeSetListener,cal.get(Calendar.HOUR_OF_DAY),
                    cal.get(Calendar.MINUTE), true).show()
            }else Toast.makeText(context,"重设请切换开关",Toast.LENGTH_SHORT).show()
        }else{
            Toast.makeText(context,"请先启用功能",Toast.LENGTH_SHORT).show()
        }
    }
}
